package com.zhidisoft.crm.controller.login;

import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.StandardPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.zhidisoft.crm.entity.SysFunction;
import com.zhidisoft.crm.entity.SysUser;
import com.zhidisoft.crm.service.ISysLoginService;
import com.zhidisoft.crm.service.ISysUserService;
import com.zhidisoft.crm.vo.AjaxVo;
import com.zhidisoft.crm.vo.LoginVo;

/**
 * auth/user/list get 默认列表(包括查询条件) <br/>
 * auth/user/${id} delete 删除<br/>
 * auth/user get 跳转到新增页面 <br/>
 * auth/user post data 新增<br/>
 * auth/user/${id} get 跳转到修改页面<br/>
 * auth/user/${id} post data 修改
 * 
 * @author REN
 *
 */

@Controller
@RequestMapping("/login")
public class LoginController {
	
	@Autowired
	ISysUserService userService;

	@Autowired
	ISysLoginService iSysLoginService;
	
	@GetMapping
	public ModelAndView login(String servletPath){

		return new ModelAndView("login/login.html","servletPath",servletPath==null||"".equals(servletPath)?"/index":servletPath);
	}
	
	@PostMapping
	@ResponseBody
	public AjaxVo login(LoginVo loginVo,HttpSession session){
			
			if(loginVo==null)
				return new AjaxVo().setErrorCode("1001").setErrorMsg("请输入用户名密码!");
			if(StringUtils.isEmpty(loginVo.getUsername()))
				return new AjaxVo().setErrorCode("1001").setErrorMsg("请输入用户名!");
			if(StringUtils.isEmpty(loginVo.getPassword()))
				return new AjaxVo().setErrorCode("1001").setErrorMsg("请输入密码");
			SysUser user = iSysLoginService.password(loginVo.getUsername());
			if(user==null)
				return new AjaxVo().setErrorCode("1001").setErrorMsg("用户名不存在");
			StandardPasswordEncoder spe = new StandardPasswordEncoder();
			if(!spe.matches(loginVo.getPassword(),user.getPassword()))
				return new AjaxVo().setErrorCode("1001").setErrorMsg("用户名不存在");
			
			List<SysFunction> sysFunctions = iSysLoginService.functions(user.getUsername());
			session.setAttribute("user", user);
			session.setAttribute("functions", sysFunctions);
			return new AjaxVo().setErrorCode("0");
		}
}
